package desktoprush;

import javax.swing.*;
import tee.binding.*;
import javax.swing.event.*;
import javax.swing.text.*;

public class RTextField extends JTextField {
    private boolean lockBinding = true;
    private Note text = new Note().afterChange(new Task() {
	@Override public void doTask() {
	    if (text != null) {
		if (!lockBinding) {
		    setText(text.value());
		}
	    }
	}
    });
    public RTextField(Document doc, String text, int columns) {
	super(doc, text, columns);
	initBinding();
    }
    public RTextField(String text, int columns) {
	super(text, columns);
	initBinding();
    }
    public RTextField(int columns) {
	super(columns);
	initBinding();
    }
    public RTextField(String text) {
	super(text);
	initBinding();
    }
    public RTextField() {
	super();
	initBinding();
    }
    public void initBinding() {
	if (!lockBinding) {
	    return;
	}
	lockBinding = false;
	getDocument().addDocumentListener(new DocumentListener() {
	    @Override public void insertUpdate(DocumentEvent e) {
		lockBinding = true;
		text.value(getText());
		lockBinding = false;
	    }
	    @Override public void removeUpdate(DocumentEvent e) {
		lockBinding = true;
		text.value(getText());
		lockBinding = false;
	    }
	    @Override public void changedUpdate(DocumentEvent e) {
		lockBinding = true;
		text.value(getText());
		lockBinding = false;
	    }
	});
    }
    public Note text() {
	return text;
    }
    public RTextField text(Note it) {
	text.bind(it);
	return this;
    }
}
